package leetcode.code;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution54 implements IDebug {

	public List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> ans = new ArrayList<>();
		int r1 = 0;
		int r2 = matrix.length - 1;
		int c1 = 0;
		int c2 = matrix[0].length - 1;
		this.f0(matrix, ans, r1, r2, c1, c2);
		return ans;
	}

	private void f0(int[][] matrix, List<Integer> ans, int r1, int r2, int c1, int c2) {
		if (c1 > c2)
			return;
		for (int i = c1; i <= c2; i++) {
			ans.add(matrix[r1][i]);
		}
		this.f1(matrix, ans, r1 + 1, r2, c1, c2);
	}

	private void f1(int[][] matrix, List<Integer> ans, int r1, int r2, int c1, int c2) {
		if (r1 > r2)
			return;
		for (int i = r1; i <= r2; i++) {
			ans.add(matrix[i][c2]);
		}
		this.f2(matrix, ans, r1, r2, c1, c2 - 1);
	}

	private void f2(int[][] matrix, List<Integer> ans, int r1, int r2, int c1, int c2) {
		if (c1 > c2)
			return;
		for (int i = c2; i >= c1; i--) {
			ans.add(matrix[r2][i]);
		}
		this.f3(matrix, ans, r1, r2 - 1, c1, c2);
	}

	private void f3(int[][] matrix, List<Integer> ans, int r1, int r2, int c1, int c2) {
		if (r1 > r2)
			return;
		for (int i = r2; i >= r1; i--) {
			ans.add(matrix[i][c1]);
		}
		this.f0(matrix, ans, r1, r2, c1 + 1, c2);
	}

	@Override
	public void debug1() {
		String str = "[[1,2,3],[4,5,6],[7,8,9]]";
		int[][] matrix = HelpDebug.str2array1(str);
		String str1 = "[1,2,3,6,9,8,7,4,5]";
		List<Integer> e = HelpDebug.str2intlist(str1);
		List<Integer> r = this.spiralOrder(matrix);
		HelpDebug.compare(e, r);
	}

	@Override
	public void debug2() {
		String str = "[[1,2,3,4],[5,6,7,8],[9,10,11,12]]";
		int[][] matrix = HelpDebug.str2array1(str);
		String str1 = "[1,2,3,4,8,12,11,10,9,5,6,7]";
		List<Integer> e = HelpDebug.str2intlist(str1);
		List<Integer> r = this.spiralOrder(matrix);
		HelpDebug.compare(e, r);
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution54 so = new Solution54();
		so.debug1();
		so.debug2();

	}

}
